package com.beaven.imclient.presenter.account;

import android.text.TextUtils;
import com.beaven.imclient.R;
import com.beaven.model.Factory;
import com.beaven.model.data.DataSource;
import com.beaven.model.data.helper.AccountHelper;
import com.beaven.model.data.helper.DbHelper;
import com.beaven.model.model.api.RspModel;
import com.beaven.model.model.api.user.UserUpdateModel;
import com.beaven.model.model.card.UserCard;
import com.beaven.model.model.db.User;
import com.beaven.model.model.sp.Account;
import rx.Subscriber;
import rx.subscriptions.CompositeSubscription;

/**
 * author: Beaven
 * time: 2017/5/25 14:44
 */

public class UpdateUserPresenter
    implements UpdateUserContract.Presenter, DataSource.FailedCallBack {

  private UpdateUserContract.View view;
  private CompositeSubscription subscription;

  public UpdateUserPresenter(UpdateUserContract.View view) {
    this.view = view;
    subscription = new CompositeSubscription();
  }

  @Override public void subscribe() {

  }

  @Override public void unSubscribe() {
    view.hideLoading();
  }

  @Override public void updateUser() {
    String nick = view.getNick();
    if (TextUtils.isEmpty(nick) || nick.length() < 2) {
      view.showText(R.string.data_account_register_invalid_parameter_name);
      return;
    }
    view.showLoading();
    UserUpdateModel model = new UserUpdateModel(nick);
    subscription.add(
        AccountHelper.updateUser(model).subscribe(new Subscriber<RspModel<UserCard>>() {
          @Override public void onCompleted() {
          }

          @Override public void onError(Throwable e) {
            view.showText(R.string.data_network_error);
            view.hideLoading();
          }

          @Override public void onNext(RspModel<UserCard> userCardRspModel) {
            if (userCardRspModel.isSuccess()) {
              DbHelper.instance().saveModel(User.class, userCardRspModel.getResult().build());
              Account.setName(userCardRspModel.getResult().getName());
              view.showText(R.string.data_account_save_success);
              view.finish();
            } else {
              Factory.decodeRspCode(userCardRspModel, UpdateUserPresenter.this);
            }
            view.hideLoading();
          }
        }));
  }

  @Override public void loadDataFail(int strRes) {
    view.showText(strRes);
  }
}
